/*
 * Copyright (c) 2008, Xiong Yingfei, the University of Tokyo
 * All rights reserved.
 */
package ac.jp.u_tokyo.SyncLib.language;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import ac.jp.u_tokyo.SyncLib.language.factories.SwitchCombinatorFactory;

public class SwitchBody extends SyncBody
{
	
	private List<SyncBody> _innerSyncs = new LinkedList<SyncBody>(); 

	public SwitchBody(int line)
	{
		super(line);
	}
	
	public void addInnerSync(SyncBody inner) {
		_innerSyncs.add(inner);
	}

	@Override
	public int getParaCount() throws EvaluationFailedException
	{
		return _innerSyncs.iterator().next().getParaCount();
	}

	static String getFactoryFullName() {
		return SwitchCombinatorFactory.class.getName();
	}
	
	void checkParaCounts() throws EvaluationFailedException {
		int n = getParaCount();
		for (SyncBody s : _innerSyncs) {
			if (n != s.getParaCount()) throw new ParameterNumberNotEqualException(s.getLine(), s.getParaCount(), getParaCount());
		}
	}
	
	@Override
	public String writeInitializeFactory(Appendable sb,
			VarNameGenerator generator, ConstMapper constMap)
			throws EvaluationFailedException, IOException
	{
		checkParaCounts();
		String newSwitch = generator.getNextName();
		sb.append(getFactoryFullName()).append(" ").append(newSwitch).append(" = new ").append(getFactoryFullName()).append("();\n");
		for (SyncBody s : _innerSyncs) {
			String newVarName = s.writeInitializeFactory(sb, generator, constMap);
			sb.append(newSwitch).append(".addFactory(").append(newVarName).append(");\n");
		}
		return newSwitch;
	}

}
